<?php

//会员指定级别在系统消费订单

function  user_buy_from_system($shopId,$uid,$grade,$limitPrice){

    $limitPrice = $limitPrice *100;
    $order = model('order')
        ->where('shopId',$shopId)
        ->where('buyUid',$uid)
        ->where('ugrade',$grade)
        ->where('totalFee','>=',$limitPrice)
        ->select();

    return $order;
}

function  user_buy_from_paidan($shopId,$uid,$grade,$limitPrice){

    $limitPrice = $limitPrice *100;
    $order = \think\Db::table('jiujiu_shop_paidan')
        ->alias('paidan')
        ->join('jiujiu_order','jiujiu_order.id=paidan.orderId','LEFT')
        ->where('paidan.shopId',$shopId)
        ->where('paidan.buid',$uid)
        ->where('paidan.bgrade',$grade)
        ->where('jiujiu_order.totalFee','>=',$limitPrice)
        ->select();

    return $order;
}




function  user_buy_from_system_count($shopId,$uid,$grade,$limitPrice){
    $order = user_buy_from_system($shopId,$uid,$grade,$limitPrice);
    return count($order);
}


function  user_buy_from_paidan_count($shopId,$uid,$grade,$limitPrice){
    $order = user_buy_from_paidan($shopId,$uid,$grade,$limitPrice);
    return count($order);
}







function changeRefund($id,$rs){
    $order = model('order')->where('id',$id)->find();
    $refund = model('refund')->where('orderId',$id)->find();
    if($rs=='reject'){
        $refund->refundStatus = 'reject';
        $refund->operateTime = time();
        $order->status2 = 7;
        $refund->save();
        $order->save();
    }
    if($rs=='success'){
        //退款到账
        $res = order_refund($order,$refund);
        if(!$res){
            //销量
            $product = model('product')->where('id',$order->productId)->find();
            $num = $order->num;
            $product->saleNum = ($product->saleNum) - $num;
            $product->save();
            $refund->refundStatus = 'success';
            $refund->operateTime = time();
            $order->status2 = 9;
            $order->status = 8;
            $refund->save();
            $order->save();
            //处理积分
            $credit = ($refund->refundFee)/100*getSettingValue('consume_credit');
            if($credit){
                $user = model('user')->where('uid',$order->buyUid)->find();
                $user->credit = $user->credit - $credit;
                $user->save();
                $history = [
                    'uid'=>$user->uid,
                    'num'=>$credit,
                    'source'=>'消费退款',
                    'cate'=>1,
                    'createTime'=>time(),
                ];
                model('credit')->insertGetId($history);

            }

            //撤销派单
            model('paidan')->where('orderId',$order->id)->where('shopId',$order->shopId)->delete();
        }

    }
    if($rs=='agree'){
        //同意退货退款
        $order->status2 = 6;
        $order->save();
    }

}

function order_refund($order,$refund){

    $refund_fee = $refund->refundFee;
    $payway = $order->payWay;
    if($payway == '微信支付'){
        if($refund_fee!=0){

            get_pay_config();
            require_once (APP_PATH.'pay/controller/weixinpay/WxPayApi.class.php');
            $input = new \WxPayRefund ();
            $input->SetOut_trade_no ( $order->payment_order_id  );//shop_order表的payment_order_id
            $input->SetTotal_fee ( $order->totalFee );
            $input->SetRefund_fee($refund->refundFee);
            $input->SetOut_refund_no($refund->id);
            $input->SetOp_user_id($order->buyUid);
            $result = \WxPayApi::refund ( $input );
            if ($result['result_code']=="FAIL" && $result['err_code'] == 'NOTENOUGH') {
                $input->SetRefund_account('REFUND_SOURCE_RECHARGE_FUNDS');
                $result = \WxPayApi::refund ( $input );
            }
            //退款成功
            if ($result['result_code'] == 'SUCCESS') {
                return '';
            }
            else{
                return $result;
            }
        }
    }

    if($payway == '余额支付'){
        $user = model('user')->where('uid',$order->buyUid)->find();
        $user->money = $user->money + $refund_fee;
        $user->save();
    }

}





/*
   * 订单支付后
   * */
function handle_order_payed($data){

    //处理订单状态问题
    $order = model('order')->where('payment_order_id',$data['out_trade_no'] )->find();
    if (!$order) {
        return false;
    }
    $order->payTime = time();
    $order->status = 1;
    $order->save();
    //销量
    $product = model('product')->where('id',$order->productId)->find();
    $num = $order->num;
    $product->saleNum = ($product->saleNum) + $num;
    $product->save();


    //处理积分
    $credit = ($order->totalFee)/100*getSettingValue('consume_credit');
    if($credit){
        $user = model('user')->where('uid',$order->buyUid)->find();
        $user->credit = $user->credit + $credit;
        $user->save();
        $history = [
            'uid'=>$user->uid,
            'num'=>$credit,
            'source'=>'消费获得',
            'cate'=>1,
            'createTime'=>time(),
        ];
        model('credit')->insertGetId($history);

    }
    return true;
}





/*
 * 关闭未付款超时订单
 * */
function cron_close_order(){
    $orders = model('order')->where('status',0)->select();//所有未付款订单
    foreach ($orders as $k=>$order){
        $time = 72*3600 + $order->createTime;
        if(time()-$time>=0){
            //超时未支付，直接删除
            model('order')->where('id',$order->id)->delete();
        }
    }
}


/*
 * 自动确认收货
 * */
function success_order(){
    $orders = model('order')->where('status',2)
        ->where('status2','<>',4)
        ->where('status2','<>',5)
        ->where('status2','<>',6)
        ->select();
    foreach ($orders as $k=>$order){

        $time = 15*24*3600 + $order->sendTime;// 默认15天
        if(time()-$time>=0){
            $order->status = 3;
            $order->save();
            //分钱
            fenqian($order);
        }
    }

}

/*
 * 手动确认收货
 * */
function user_success_order($id){
    $order = model('order')->where('id',$id)->find();
    if($order->status2==4 || $order->status2==5 ||$order->status2==6){
        $order->status2 = 0;
        model('refund')->where('orderId',$id)->delete();
    }
    $order->status = 3;
    $order->save();
    //分钱
    fenqian($order);
}


function fenqian($order){
    $shop = model('shop')->where('id',$order->shopId)->find(); //代理
    $product = model('product')->where('id',$order->productId)->find(); //货源
    $totalFee = $order->totalFee;
    $costPrice = $order->costPrice; //成本，给货源
    $lirun = $totalFee-$costPrice; //利润给代理
    if($shop->owner!='system'){
        model('user')->where('uid',$shop->owner)->setInc('money',$lirun);
    }
    if($product->uid!=0){
       model('user')->where('uid',$product->uid)->setInc('money',$costPrice);
    }



}



function get_pay_config(){

    $paymentSet ['wxappid'] = 'wx59f06d4e5a0414fa';
    $paymentSet ['wxpaysignkey'] = 'ZXCzxczxczxczxczxczxczxczxczxc12';
    $paymentSet ['wxappsecret'] = '66f8e1b559f195333915e9efbe738ac4';
    $paymentSet ['wxmchid'] = 1336648101;
    $paymentSet ['cert_path'] =ROOT_PATH .'application/pay/cert/apiclient_cert.pem';
    $paymentSet ['key_path'] = ROOT_PATH .'application/pay/cert/apiclient_key.pem' ;
    \think\Session::set( 'paymentinfo', $paymentSet );
}

